<template>
  <a-drawer v-model:visible="vdata.visible" width="40%" :mask-closable="false" @close="close">
    <template #title>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <span>商户数据对比</span>
        <!-- <a-button type="link" @click="exportCode(vdata.record)">导出渠道</a-button> -->
      </div>
    </template>
    <div class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="fileList">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <!-- <a href="https://jdyd-test.oss-cn-hangzhou.aliyuncs.com/download/c19c2bf1-2ee0-436f-8ef7-19afe3d09e9d.xlsx" download="https://jdyd-test.oss-cn-hangzhou.aliyuncs.com/download/c19c2bf1-2ee0-436f-8ef7-19afe3d09e9d.xlsx">商户数据对比模板下载</a> -->
                <a-button type="link" style="padding:  4px 0;" @click="exportToExcel('商户数据对比模板',['商户号', '微信间连号', '支付宝间连号'],['','',''])">
                  商户数据对比模板下载
                </a-button>
              </template>
              <a-upload-dragger
                v-model:fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                bizType="template"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
          
          <!-- <a-col :span="24">
            <span style="margin-right: 20px">结果</span>
            <a-button type="link" :href="vdata.resultSC.successUrl" style="margin: 0;">
              {{ vdata.resultSC.successUrl }}
            </a-button>
          </a-col>
          
          <a-col :span="24">
            <span style="margin-right: 20px">结果</span>
            <a-button type="link" :href="vdata.resultSC?.failUrl" style="margin: 0;">
              {{ vdata.resultSC.failUrl }}
            </a-button>
          </a-col> -->
        </a-row>
      </a-form>
      <!-- 列表展示 -->
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { reactive, getCurrentInstance } from 'vue'
import request from '@/http/request'
import { exportToExcel } from '@/utils/excelUtils'

import { req, API_MCHINFO_COMPARE, $getUploadFormParams, } from '@/api/manage'
import {$apiMchInfoCompare} from '@/api/operateTool/index'

import * as XLSX from 'xlsx'
const props = defineProps(['callBackFunc'])
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const vdata = reactive({
  visible: false,
  saveObject: {
    fileList: []
  },
  ossFileUrl: '',
  action: '', //上传地址
  formParams: '',
  resultSC:{
    failUrl:'',
    successUrl:''
  }
})

/**
 * 文件上传
 */
function beforeUpload(file) {
  console.log('file', file)
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.ossFileUrl = res.ossFileUrl
  })
}

function uploadChange(info) {
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功
    console.log(vdata.ossFileUrl,'上传后的文件地址')
    $apiMchInfoCompare({ ossFileUrl: vdata.ossFileUrl }).then(res=>{
      console.log(res,'上传成功后的文件')
      // vdata.resultSC.failUrl = res.data?.failUrl
      // vdata.resultSC.successUrl = res.data?.successUrl
      const failUrl = res.failUrl
      const successUrl = res.successUrl

      if(failUrl){
          const link = document.createElement('a')
          link.href = failUrl
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
      }

      if(successUrl){
          setTimeout(() => {
            const link = document.createElement('a')
          link.href = successUrl
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          }, 200)
      }
      
      
    })
    // request.exportExcel(API_MCHINFO_COMPARE, { ossFileUrl: vdata.ossFileUrl }, 'GET', '商户数据对比结果.xlsx').then(res => {
    //   console.log('res', res)
    // })
    // req.list(API_MCHINFO_COMPARE,{ossFileUrl:vdata.ossFileUrl}).then(res=>{
    //     console.log(res)
    // })
  }
}

const close = () => {
  vdata.visible = false
}


// // excel表格导出函数数据
// const exportToExcel = (item, name) => {
//   // 创建一个工作簿
//   const workbook = XLSX.utils.book_new()

//   // 创建一个工作表
//   const worksheet = XLSX.utils.aoa_to_sheet([...item])

//   // 将工作表添加到工作簿
//   XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

//   // 生成Excel文件
//   XLSX.writeFile(workbook, `${name}.xlsx`)
// }

// // 商户模板下载
// function merchantTemplate() {
//   let tempalteInformation = undefined
//   let tempalteName
//   tempalteName = '商户数据对比模板下载'
//   tempalteInformation = [
//     ['商户号', '微信间连号', '支付宝间连号'],

//   ]
//   exportToExcel(tempalteInformation, tempalteName)
// }

/**
 * 展开
 */
async function show(record) {
  vdata.visible = true
}

defineExpose({
  show,
})
</script>
<style lang="less"></style>